package Servlet;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.StyledEditorKit.BoldAction;


import DBModule.CourseTable;
import DBModule.QuestionTable;
import DBModule.TestPaperManager;
import Interact.Interface;
import Test.Question;
import Test.QuestionBody;
import Test.TestPaper;
import Test.TestPaperState;
import User.User;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			String method = request.getParameter("method");
	        if (method == null) {
	            response.sendRedirect("index.jsp");
	        }
	        else if (method.equalsIgnoreCase("select")){
	        	select(request, response);
	        }
	        else if (method.equalsIgnoreCase("save")){
	        	save(request, response);
	        }
	        else if (method.equalsIgnoreCase("setquestionbody")){
	        	setQuestionBody(request, response);
	        }
	        else if (method.equalsIgnoreCase("correct")){
	        	correct(request, response);
	        }
		}
		catch(Exception exp){
			HttpSession session = request.getSession();
			exp.printStackTrace();
			String msg = exp.getMessage();
			if (msg == null) msg = "内部错误";
			session.setAttribute("alert", msg);
			response.sendRedirect("alert.jsp");
//			request.getRequestDispatcher("/alert.jsp").forward(request, response);
		}
	}
	
	protected void select(HttpServletRequest req, HttpServletResponse res) throws Exception{
		req.getSession().setAttribute("course", CourseTable.getCourse(Integer.parseInt(req.getParameter("course"))));
		res.sendRedirect("testing.jsp");
	}
	
	/**
	 * 自动审阅可审阅题目
	 * @param paper	试卷
	 */
	private static void autoCheck(TestPaper paper){
		Iterator<Question> iter = paper.getQuestions().iterator();
		boolean flag = true;
		int score = 0;
		while (iter.hasNext()){
			int s = iter.next().correct();
			if (s >= 0) score += s;
			else flag = false;
		}
		TestPaperState state = paper.getState();
		if (!flag) state.setState(TestPaper.UNCORRECT);
		else {
			state.setScore(score);
			state.setState(TestPaper.CORRECTED);
		}
	}
	
	protected void save(HttpServletRequest req, HttpServletResponse res) throws Exception{
		// 取试卷
		TestPaper paper = (TestPaper)req.getSession().getAttribute("paper");
		if (paper == null) throw new Exception("未提交试卷");
		
		Interface inf = new Interface(req, res);
		// 设置学生答案
		paper.setValueViaInterface(inf);
		
		// 审阅可被自动审阅的部分
		autoCheck(paper);
		
		// 保存试卷
		TestPaperManager.insertPaper(paper);
		
		Alert.setAlertMsg(req, "提交成功", "student.jsp", "green");
		res.sendRedirect("alert.jsp");
	}
	
	protected void setQuestionBody(HttpServletRequest req, HttpServletResponse res) throws Exception{
		QuestionBody body = (QuestionBody)req.getSession().getAttribute("body");
		if (body == null) throw new Exception("未创建试题");
		
		Interface inf = new Interface(req, res);
		body.setValueViaInterface(inf);
		
		body.setCourse(CourseTable.getCourse(Integer.parseInt(req.getParameter("course"))));
		body.setGrade(Integer.parseInt(req.getParameter("grade")));
		
		QuestionTable.insertAsDefaultID(body);
		Alert.setAlertMsg(req, "成功创建试题，该题目ID为" + body.getId(), "teacher.jsp", "green");
		res.sendRedirect("alert.jsp");
	}
	
	protected void correct(HttpServletRequest req, HttpServletResponse res) throws Exception{
		// 用户
		User teacher = (User)req.getSession().getAttribute("user");
		if (teacher == null || teacher.getType() != User.TEACHER)
			throw new Exception("用户未登陆，或不是教师");
		
		// 取试卷
		TestPaper paper = (TestPaper)req.getSession().getAttribute("paper");
		if (paper == null) throw new Exception("未提交试卷");
		
		paper.setMode(Question.CORRECT_MODE);
		Interface inf = new Interface(req, res);
		
		// 设置答案
		paper.setValueViaInterface(inf);
		
		Iterator<Question> iter = paper.getQuestions().iterator();
		
		// 设置评卷人，原则上每道题的评卷老师都不一定一样，这里为了省事设成一样的了
		while (iter.hasNext())
			iter.next().getContent().setTeacherID(teacher.getID());

		int state;
		try{state = Integer.parseInt(req.getParameter("state"));}
		catch (Exception e){state = TestPaper.UNCORRECT;}
		
		paper.getState().setState(state);
		if (state == TestPaper.CORRECTED)
			paper.calculateScore();
		
		TestPaperManager.savePaper(paper);
		Alert.toAlert(res, req, "批阅成功", "teacher.jsp", "green");
	}
}






